package com.wxy.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.config.interceptor;
import com.wxy.dao.userMapper;
import com.wxy.domain.R;
import com.wxy.domain.User;
import com.wxy.domain.myException;
import com.wxy.service.userService;

import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;


@Controller
@RequestMapping("/my")
public class myController {
	private static final Logger LOGGER=LoggerFactory.getLogger(myController.class);
	@Autowired
	private userService userService;
	@Autowired
	private userMapper userMapper;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	private static final int TIME=2;
	@GetMapping("/test1/{id}")
	@ResponseBody
	@Operation(summary = "根据id查询用户",description = "根据id查询用户，返回一个R类型的对象.")
	@ApiResponses(value = @ApiResponse(responseCode = "200",description = "获取成功...",content = @Content))
	public R test1(@PathVariable int id) {
		return R.ok("查询成功",userService.findById(id));
	}
	
	@GetMapping("/test2/{id}")
	@ResponseBody
	@Operation(summary = "根据id查询用户",description = "根据id查询用户，返回一个user实例")
	@ApiResponse(responseCode = "200",description = "获取成功...",content = @Content)
	public User test2(@PathVariable(value = "id") int id) {
		return userService.findById2(id);
	}
	
	@GetMapping("test3")
	@ResponseBody
	@Operation(summary = "模拟一个异常",description = "模拟一个异常用来测试全局异常处理器")
	@ApiResponse(responseCode = "400",description = "aaa错误,跳转到error.html页面",content = @Content)
	public int test3() {
		int i=1/1;
		throw new myException("aaa");
	}
	
//	@RequestMapping("/getUserByPage")				//mybatis-plus的分页查询，返回值为list集合
//	@ResponseBody
//	public Object getUserByPage(@RequestParam("page") int page,@RequestParam("size") int size){
//		Page<User> pageRequestPage=new Page<>(page,size);
//		IPage<User> resultPage=userMapper.selectPage(pageRequestPage,null);
//		List<User> records=resultPage.getRecords();
//		if(records.isEmpty()) {
//			System.out.println("null");
//			return "已经是最后一条数据了...";}
//		System.out.println(records);
//		return records;
//	}
	@GetMapping("/getUserByPage")				//mybatis-plus的分页查询，返回值为R
	@ResponseBody
	@Operation(summary = "mp的分页查询",description = "mp的分页查询，返回一个R实例给前端")
	@ApiResponse(responseCode = "200",description = "查询成功",content=@Content)
	public R getUserByPage(@RequestParam("page") int page,@RequestParam("size") int size){
		Page<User> pageRequestPage=new Page<>(page,size);
		List<User> records=new ArrayList<User>();
		//根据id从redis中查询
		for(int i=((page-1)*size+1);i<=page*size;i++) {
			//查不到，跳出循环
			if(stringRedisTemplate.opsForValue().get("user:"+i)==null)
				break;
			//查到了，存入集合中
			else {
				String userJsonString=stringRedisTemplate.opsForValue().get("user:"+i);
				records.add(JSONUtil.toBean(userJsonString,User.class) );
			}
		}
		//集合判空，不为空，返回数据
		if(!records.isEmpty()) {
			return R.ok("查询成功",records);
		}
		//redis中没有查到数据，从数据库中查询
		IPage<User> resultPage=userMapper.selectPage(pageRequestPage,null);
		records=resultPage.getRecords();
		if(records.isEmpty()) {
			System.out.println("null");
			return R.ok("已经是最后一条数据了...");
		}
		//查到数据，存入redis中
		for (User user : records) {
			stringRedisTemplate.opsForValue().set("user:"+user.getId(),JSONUtil.toJsonStr(user),TIME,TimeUnit.MINUTES);
		}
		System.out.println(records);
		return R.ok("查询成功",records);
	}
}
